//#include <apue.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

int jdup2(int filedes, int filedes2)
{
	printf("enter jdup2().\n");

	if (filedes == filedes2) {
		return filedes;
	}

	int fd = 0;
	int *tmpfd = NULL;
	char *fdpath = NULL;
	fdpath = (char*)malloc(sizeof(char) * 15);

	sprintf(fdpath, "/dev/fd/%d", filedes);
	if (open(fdpath, O_RDONLY) == -1) {
		fprintf(stderr, "open(%s) failed.\n", fdpath);
		exit(-1);
	}

	if (close(filedes2) == -1) {
		fprintf(stderr, "close(%d) failed.\n", filedes2);
		exit(-1);
	}
	sprintf(fdpath, "/dev/fd/%d", filedes2);
	if (open(fdpath, O_RDONLY) == -1) {
		printf("open(%s) failed.\n", fdpath);
	}
	free(fdpath);

	tmpfd = (int*)malloc((filedes2-filedes)*sizeof(int));
	int i = 0;
	do {
		if ((tmpfd[i] = dup(filedes)) == -1) {
			fprintf(stderr, "open(%d) failed.\n", filedes);
			return filedes;
		}
	} while (tmpfd[i++] < filedes2);

	int p;
	for (p = 0; p < i-1; p++) {
		close(tmpfd[p]);
	}
	fd = tmpfd[--i];
	free(tmpfd);

	return fd;
}

int main (int argc, char *argv[])
{
	if (argc != 3) {
		printf("[USAGE] %s filename filename2\n", argv[0]);
		exit(1);
	}

	int fd1 = 0;
	int fd2 = 0;
       	if ((fd1 = open(argv[1], O_RDWR)) == -1) {
		fprintf(stderr, "open(%s) failed.\n", argv[1]);
	}
	printf("filedes1[%s] = %d.\n", argv[1], fd1);
       	
	if ((fd2 = open(argv[2], O_RDWR)) == -1) {
		fprintf(stderr, "open(%s) failed.\n", argv[2]);
	}
	printf("filedes2[%s] = %d.\n", argv[2], fd2);

	int fd = jdup2(fd1, fd2);
	printf("after jdup2() : fd = %d\n", fd);

	printf("\n********************************************\n"
	       "PRINT file[%d]"
	       "\n********************************************\n", fd);
	char buf[51] = {0};
	size_t s = 0;
	while ((s = read(fd, buf, 50)) != 0) {
		buf[s] = '\0';
		printf("%s", buf);
	}

	exit(0);
}

